package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.IdName;
import com.fuershiye.woman.monitor.beans.Result;
import com.fuershiye.woman.monitor.beans.ViewIndicatorType;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.Forms;
import com.fuershiye.woman.monitor.model.IndicatorType;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.BaseUtil;
import com.fuershiye.woman.monitor.utils.MyUtilString;
import com.fuershiye.woman.monitor.utils.ObjectUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * 
 * 指标类型，也叫领域
 *
 */
@Controller
@RequestMapping(value = "/indicator/type")
@SuppressWarnings("unchecked")
public class IndicatorTypeController {
	
	private static final Logger logger = LoggerFactory.getLogger(IndicatorTypeController.class);

	@Autowired
	IndicatorTypeService indicatorTypeService;
	@Autowired
	DepartIndicatorService departIndicatorService;
	@Autowired
	IndicatorService indicatorService;
	@Autowired
	UserService userService;
	@Autowired
	FormsService formsService;

//    @RequiresPermissions("indicatorType:view")
    @RequestMapping(value="/view.do")
    public String view(String show, Model model){

		List<IdName> allForms = formsService.getAllNames();
		model.addAttribute("allForms", allForms);

		return "indicator/" + show;
    }

	//    @RequiresPermissions("indicatorType:list")
	@RequestMapping(value="/get.do")
	@ResponseBody
	public List<ViewIndicatorType> getByids(String idStr, Long formsid, String name) {
		List<Long> ids = MyUtilString.str2LongByPlaceHolder(idStr, ",");
		List<IndicatorType> list = indicatorTypeService.listByCondition(ids, formsid, name, 1);
		return ObjectUtil.turnIndicatorType(list);
	}

//    @RequiresPermissions("indicatorType:list")
    @RequestMapping(value="/list.do")
    @ResponseBody
    public List<IndicatorType> list(Long formsid, String name) {
		return indicatorTypeService.listByCondition(formsid, name, 1);
    }
    
//    @RequiresPermissions("indicatorType:all")
//    @SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/all.do")
    @ResponseBody
    public Result all(Long formsid) {

		if(formsid==null){
			return new Result(Massage.ERROR_PARAMETER);
		}
		int status = 1;
		return new Result(Massage.SUCCESS, indicatorTypeService.getByCondition(formsid, "", status));
		
    }

	@RequestMapping(value="/self.do")
    @ResponseBody
    public Result self(Long formsid, Integer year) {

		// 1、获取当前用户
		String name = SecurityUtils.getSubject().getPrincipal() + "";
		if(StringUtils.isEmpty(name)){
			return null;
		}
		// 2、获取当前用户所在部门
		Department department = userService.getDepartIdByName(name);

		// 3、获取当前用户当前年份存在的指标
		List<Long> indicators= departIndicatorService.listIndicatorsByCondition(Arrays.asList(department.getId()), formsid, Arrays.asList(year));
		indicators = BaseUtil.removeDuplicateList(indicators);

		// 4、根据指标获取所有指标类型
		List<Long> typeIds= indicatorService.getTypeIdsByCondition(formsid, indicators);
		typeIds = BaseUtil.removeDuplicateList(typeIds);
		List<IdName> indicatorTypeIdNames = indicatorTypeService.getByCondition(formsid, typeIds);
		indicatorTypeIdNames = BaseUtil.removeDuplicateIdName(indicatorTypeIdNames);

		return new Result(Massage.SUCCESS, indicatorTypeIdNames);
    }

    @RequestMapping(value = "/save.do")
    @ResponseBody
    public Result save(Long id, Long formsid, String code, String name,
					   String making, String number, String rate, String remark, Integer expire) {

		if(formsid==null||formsid==0 || StringUtils.isEmpty(name)){
			return new Result(Massage.ERROR_PARAMETER);
		}

    	IndicatorType it = null;
    	boolean add = false;
    	if(id==null || id==0){
    		add = true;
        	it = new IndicatorType();
			it.setCtime(new Date());
    	}else{
    		it = indicatorTypeService.get(id);
    		if(it==null){
        		logger.error("IndicatorTypeController update,IndicatorType is null");
				return new Result(Massage.INDICATOR_TYPE_IS_NULL);
        	}
    	}

		Forms forms = formsService.get(formsid);
		if(forms==null){
			return new Result(Massage.FORMS_IS_NULL);
		}

		it.setFormsid(formsid);
		it.setCode(code);
		it.setName(name);
		it.setMaking(making);
		it.setNumber(number);
		it.setRate(rate);
		it.setRemark(remark);
		it.setEditor(SecurityUtils.getSubject().getPrincipal()+"");
		it.setExpire(expire);

    	it.setStatus(1);
		it.setMtime(new Date());
    	indicatorTypeService.save(it);
    	
    	//如果是新加的则给默认的排序号sort(主键id)
    	if(add){
    		IndicatorType top = indicatorTypeService.getTop();
			if(top==null){
				return new Result(Massage.INDICATOR_TYPE_IS_NULL);
			}
			it.setSort(top.getId());
			indicatorTypeService.save(it);
    	}
		return new Result(Massage.SUCCESS);
    }
    
    /**
     * @param id	要排序的数据
     * @param aim	1:升序; 2:降序
     * @return
     */
//    @RequiresPermissions("indicatorType:sort")
    @RequestMapping(value = "/sort.do")
    @ResponseBody
    public boolean sort(Long id, Integer aim) {
    	
    	if(id==null||(aim!=1&&aim!=2)){
        	logger.info("IndicatorTypeController sort id null, id:{},aim:{}",id,aim);
    		return false;
    	}
    	IndicatorType it = indicatorTypeService.get(id);
    	if(it==null){
        	logger.error("IndicatorTypeController IndicatorType null, id:{}",id);
    		return false;
    	}
    	
		IndicatorType top = indicatorTypeService.findBySort(it.getSort(),aim,1);
		if(top==null){
			//查不到需要交换的对象,则认为交换成功
    		return true;
    	}
		//交换序号
		long temp = it.getSort();
		it.setSort(top.getSort());
		top.setSort(temp);
		//保存
    	indicatorTypeService.save(it);
    	indicatorTypeService.save(top);
    	return true;
    }
    
//    @RequiresPermissions("indicatorType:delete")
    @RequestMapping(value="/delete.do")
    @ResponseBody
    public boolean delete(Long id) {
    	IndicatorType it = indicatorTypeService.get(id);
    	it.setStatus(0);//修改为已删除
    	indicatorTypeService.save(it);
        return true;
    }

}
